﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO.Ports;
using System.Threading;


namespace chromemeter
{
    public partial class FormMain : Form
    {
        public FormMain()
        {
            InitializeComponent();
        }
        #region 电源变量
        private ClassSourceMeter classSourceMeter = new ClassSourceMeter();
        private bool sourceIsJoin;
        private double currLimit=1;
        private double voltLimit=4;
        private double voltMax=12;
        private double voltMin=0;
        private double currMin=0.001;
        private double currMax=0.06;
        private double voltSpace=0.2;
        private double currSpace=0.001;
        private int iTimeSpace=2;
        private int vTimeSpace=2;
        private double[] voltCheck;
        private double[] currCheck;
        private int vcount=1;
        private int icount=1;
        private string recv;
        private int num;
        int index = 1;
        private double currSet;
        private double voltSet;
        private double currRev;
        private double voltRev;
        #endregion
        #region 光度计变量
        private ClassChromeMeter classChromeMeter = new ClassChromeMeter();
        //private int nTime;
        private string cBuf;
        private string cBuf1;
        private string[] cBuf2;
        private double cLv;
        private double cX;
        private double cY;
        private string recv1;
        private bool chromeIsJoin;
        private double[] clv;
        private double[] cx;
        private double[] cy;
        #endregion


        #region 其它变量
        private bool isMeasure = false;
        private string[] information;
        private Thread threadMeasure;
        private delegate void dlgShowButton();
        private delegate void chromeMeasure();
        private delegate void dlgDisplay1();
        int a = 0;
        #endregion

        #region 功能函数

        private void enableButton()
        {
            tlClear.Enabled = true;
            tlSave.Enabled = true;
            tlSetting.Enabled = true;
            tlMeasure.Enabled = true;
        }

        private void unableButton()
        {
            tlClear.Enabled = false;
            tlSave.Enabled = false;
            tlSetting.Enabled = false;
            tlMeasure.Enabled = false;
        }

        private void output()
        {
            int[] dataCount = new int[dgvList.ColumnCount - 1];

            for (int i = 0; i < dataCount.Length; i++)
            {
                dataCount[i] = 1;
            }

            SaveFileDialog sfdOutput = new SaveFileDialog();

            sfdOutput.Filter = "files (*.xls)|*.xls";
            sfdOutput.FilterIndex = 0;
            sfdOutput.Title = "保存为Excel文件";
            sfdOutput.FileName = DateTime.Now.ToString("yyyyMMdd") + DateTime.Now.Hour.ToString("00") + DateTime.Now.Minute.ToString("00"); //默认保存文件名
            if (sfdOutput.ShowDialog() == DialogResult.OK)
            {
                ClassExportExcel classExportExcel = new ClassExportExcel();
                classExportExcel.StartThread(dgvList, information, dataCount, sfdOutput.FileName);
            }
        }

        private void measureSourceVolt()
        {
            a = 0;
            if (isMeasure)
            {
                num = (int)(1+ (voltMax - voltMin) / voltSpace);
                int i = 0;
                int j = 0;
                int k = 0;
               

                double[] lv = new double[num];
                double[] x = new double[num];
                double[] y = new double[num];
                voltSet = voltMin;
                classSourceMeter.InitVolt(currLimit);
                do
                {
                    classSourceMeter.SourVolt(voltSet);
                    Vcmeasure(ref cLv, ref cX, ref cY);
                    lv[i] = cLv;
                    x[j] = cX;
                    y[k] = cY;
                    i++;
                    j++;
                    k++;
                   
                    voltSet += voltSpace;
                }
                while (i!=num);
                classSourceMeter.CurrMeasure(ref num, ref voltCheck, ref currCheck);
                clv = lv;
                cx = x;
                cy = y;

                classSourceMeter.LightOff();
                //Thread.Sleep(3000);
                //classChromeMeter.exit();




                BeginInvoke(new dlgShowButton(enableButton));
                isMeasure = false;
                MessageBox.Show("测试完成！", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }

            threadMeasure.Abort();
        }

       /*private void measureSourceCurr()
        {
            a = 0;
            if (isMeasure)
            {
                int time = 0;
                num = (int)(1.1+(currMax - currMin) / currSpace);
                
                int i = 0;
                int j = 0;
                int k = 0;
                double[] lv = new double[num];
                double[] x = new double[num];
                double[] y = new double[num];
                classSourceMeter.CurrSweep(currMin, currMax, currSpace, iTimeSpace, icount, num, voltLimit);
                do
                {
                    
                    Icmeasure(ref cLv, ref cX, ref cY);
                    lv[i] = cLv;
                    x[j] = cX;
                    y[k] = cY;
                    i++; 
                    j++; 
                    k++;
                    time += iTimeSpace;
                }
                while (time < num * iTimeSpace);
                clv = lv;
                cx = x;
                cy = y;
                //classSourceMeter.VoltMeasure(ref recv, ref voltCheck, ref  currCheck);
                Thread.Sleep(3000);
                //classSourceMeter.VoltMeasure(ref recv, ref currCheck, ref  voltCheck);
                do
                {
                    classSourceMeter.VoltMeasure(ref recv, ref currCheck, ref  voltCheck);
                }
                while (voltCheck.Length != num);
                

                isMeasure = false;
                BeginInvoke(new dlgShowButton(enableButton));
                MessageBox.Show("测试完成！", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }

            threadMeasure.Abort();
        }*/


        private void measureSourceCurr()
        {
            a = 0;
            if (isMeasure)
            {
                num = (int)(1 + (currMax - currMin) / currSpace);
                int i = 0;
                int j = 0;
                int k = 0;
            
               
                double[] lv = new double[num];
                double[] x = new double[num];
                double[] y = new double[num];
                currSet = currMin;
                classSourceMeter.InitCurr(voltLimit);
                do
                {
                    classSourceMeter.SourCurr(currSet); 
                    Icmeasure(ref cLv, ref cX, ref cY);
                    lv[i] = cLv;
                    x[j] = cX;
                    y[k] = cY;
                    i++;
                    j++;
                    k++;
                    currSet +=currSpace;
                }
                while (i != num);
                classSourceMeter.VoltMeasure(ref num, ref voltCheck, ref currCheck);
                clv = lv;
                cx = x;
                cy = y;
              
                classSourceMeter.LightOff();
                //Thread.Sleep(3000);
                
               



                BeginInvoke(new dlgShowButton(enableButton));
                isMeasure = false;
                MessageBox.Show("测试完成！", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }

            threadMeasure.Abort();
        }
       private void display()
        {
            int index = 1;
            DataGridViewRow row = new DataGridViewRow();
            row.CreateCells(dgvList);

            row.Cells[0].Value = index.ToString("#00");
            row.Cells[1].Value = cLv.ToString("#0.0000");
            row.Cells[2].Value = cX.ToString("#0.0000");
            row.Cells[3].Value = cY.ToString("#0.0000");

            dgvList.Rows.Add(row);

            index++;
        }
       private void Vcmeasure(ref double lv, ref double x,ref double y)
       {
               //int i = 1;
               int nTime;
               //Thread.Sleep(vTimeSpace* 250-100);
               classChromeMeter.RMT();
               cBuf = classChromeMeter.MES();
               if (cBuf.Substring(0, 2) == "ER")
               {
                   lv = 1;
                   x = 1;
                   y = 1;
                   Thread.Sleep(1000);
                   
               }
               else
               {
                   recv1 = cBuf.Substring(6, 1);
                   nTime = Convert.ToInt32(recv1);
                   Thread.Sleep(nTime * 1000-500);
                   classChromeMeter.MDR();
                   Thread.Sleep(300);
                   cBuf1 = classChromeMeter.MDR();
                   if (cBuf1.Substring(0, 2) == "OK")
                   {
                       cBuf2 = cBuf1.Split(',');
                       lv = Convert.ToDouble(cBuf2[9]);
                       x = Convert.ToDouble(cBuf2[10]);
                       y = Convert.ToDouble(cBuf2[11]);
                       //Thread.Sleep(vTimeSpace*1000  - nTime * 1000-75+88);


                   }
                   else
                   {
                       Thread.Sleep(300);
                       lv = 0;
                       x = 0;
                       y = 0;
                       Thread.Sleep(700);
                      
                   }
               }

       }


       private void Icmeasure(ref double lv, ref double x, ref double y)
       {
           //int i = 1;
           int nTime;
           //Thread.Sleep(iTimeSpace * 250);
           classChromeMeter.RMT();
           cBuf = classChromeMeter.MES();
           if (cBuf.Substring(0, 2) == "ER")
           {
               lv = 1;
               x = 1;
               y = 1;
               Thread.Sleep(1000);
               
           }
           else
           {
               recv1 = cBuf.Substring(6, 1);
               nTime = Convert.ToInt32(recv1);
               Thread.Sleep(nTime * 1000 - 500);
               classChromeMeter.MDR();
               cBuf1 = classChromeMeter.MDR();
               if (cBuf1.Substring(0, 2) == "OK")
               {
                   cBuf2 = cBuf1.Split(',');
                   lv = Convert.ToDouble(cBuf2[9]);
                   x = Convert.ToDouble(cBuf2[10]);
                   y = Convert.ToDouble(cBuf2[11]);
                   //Thread.Sleep(iTimeSpace * 1000 - nTime * 1000 +14);


               }
               else
               {
                   Thread.Sleep(300);
                   lv = 0;
                   x = 0;
                   y = 0;
                   Thread.Sleep(700);
                  
               }
           }

       }
        /*private int cmeasure()
        {
            int time = 0;
            int i = 0;
            do
            {
             Thread.Sleep(iTimeSpace / 4);
             classChromeMeter.RMT();
            cBuf = classChromeMeter.MES();
            recv1 = cBuf.Substring(5, 2);
            nTime = int.Parse(recv1);
            Thread.Sleep(nTime * 1000 - 500);
            classChromeMeter.MDR();
            cBuf1 = classChromeMeter.MDR();
            cBuf2 = cBuf1.Split(',');
            lv = Convert.ToDouble(cBuf2[9]);
            x = Convert.ToDouble(cBuf2[10]);
            y = Convert.ToDouble(cBuf2[11]);
            //BeginInvoke(new dlgDisplay(display));
            time+=iTimeSpace;
            }
            while (time == num * iTimeSpace);
            return i;

        }*/
        private void clear()
        {

            dgvList.Rows.Clear();
            chartChrome1.ChartGroups.ChartGroupsCollection[0].ChartData.SeriesList[0].PointData.Clear();
            chartChrome2.ChartGroups.ChartGroupsCollection[0].ChartData.SeriesList[0].PointData.Clear();

        }

        private void display1()
        {   
            
            
           DataGridViewRow row = new DataGridViewRow();
           row.CreateCells(dgvList);
           //row.Cells[0].Value = index.ToString("#00");
           row.Cells[1].Value = clv[a].ToString("#0.0000");
           row.Cells[2].Value = cx[a].ToString("#0.0000");
           row.Cells[3].Value = cy[a].ToString("#0.0000");
           row.Cells[4].Value = voltCheck[a].ToString("#0.000000");
           row.Cells[5].Value = currCheck[a].ToString("#0.000000");
           dgvList.Rows.Add(row);
           //index++;

           chartChrome1.ChartGroups.ChartGroupsCollection[0].ChartData.SeriesList[0].PointData.Clear();
           chartChrome2.ChartGroups.ChartGroupsCollection[0].ChartData.SeriesList[0].PointData.Clear();
           for (int i = 0; i < voltCheck.Length; i++)
           {
               chartChrome1.ChartGroups.ChartGroupsCollection[0].ChartData.SeriesList[0].X.Add(voltCheck[i]);
               chartChrome1.ChartGroups.ChartGroupsCollection[0].ChartData.SeriesList[0].Y.Add(clv[i]);
           }
           chartChrome2.ChartGroups.ChartGroupsCollection[0].ChartData.SeriesList[0].PointData.Clear();

           for (int i = 0; i < currCheck.Length; i++)
           {
               chartChrome2.ChartGroups.ChartGroupsCollection[0].ChartData.SeriesList[0].X.Add(currCheck[i]);
               chartChrome2.ChartGroups.ChartGroupsCollection[0].ChartData.SeriesList[0].Y.Add(clv[i]);
           }
        }

        #endregion

        #region 窗体事件
        private void FormMain_Load(object sender, EventArgs e)
        {
            // loadConfig();

            classSourceMeter.Join();


            if (classSourceMeter.Join() == 0)
            {
                sourceIsJoin = true;
                tllSource.Text = "电源已连接";
                tllSource.ForeColor = Color.Black;
            }
            else
            {
                sourceIsJoin = false;
                tllSource.Text = "电源未连接";
                tllSource.ForeColor = Color.Red;
            }

            if (classChromeMeter.join() == 0)
            {
                chromeIsJoin = true;
                tllChrome.Text = "光度计已连接";
                tllChrome.ForeColor = Color.Black;
            }
            else
            {
                chromeIsJoin = false;
                tllChrome.Text = "光度计未连接";
                tllChrome.ForeColor = Color.Red;
            }
            /*voltMax = voltSet;
            voltMin = voltSet * 0.5;
            voltSpace = voltSet / 10;*/

            clear();
        }

        private void FormMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (isMeasure)
            {
                MessageBox.Show("正在测试！", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                if (sourceIsJoin)
                {
                    classSourceMeter.Eixt();
                }

                if (chromeIsJoin)
                {
                    classChromeMeter.exit();
                }

                if (threadMeasure != null)
                {
                    if (threadMeasure.IsAlive)
                    {
                        threadMeasure.Abort();
                    }
                }

                //saveConfig();
                clear();
            }
        }
        #endregion

        #region 按钮事件
        private void tlSave_Click(object sender, EventArgs e)
        {
            if (dgvList.Rows.Count == 0)
            {
                return;
            }
            else
            {
                output();
            }
        }

        private void tlClear_Click(object sender, EventArgs e)
        {
            clear();
        }
        private void tlJoin_Click(object sender, EventArgs e)
        {
            classChromeMeter.join();
            if (classChromeMeter.join() == 0)
            {
                chromeIsJoin = true;
                tllChrome.Text = "光度计已连接";
                tllChrome.ForeColor = Color.Black;
            }
            else
            {
                chromeIsJoin = false;
                tllChrome.Text = "光度计未连接";
                tllChrome.ForeColor = Color.Red;
            }
            classSourceMeter.Join();
            if (classSourceMeter.Join() == 0)
            {
                sourceIsJoin = true;
                tllSource.Text = "电源已连接";
                tllSource.ForeColor = Color.Black;
            }
            else
            {
                sourceIsJoin = false;
                tllSource.Text = "电源未连接";
                tllSource.ForeColor = Color.Red;
            }
        }
        private void tlSetting_Click(object sender, EventArgs e)
        {

            FormSetting frm_Setting = new FormSetting();
            frm_Setting.VoltLimit = voltLimit;
            frm_Setting.CurrMax = currMax;
            frm_Setting.CurrMin = currMin;
            frm_Setting.CurrSpace = currSpace;
            frm_Setting.ITimeSpace = iTimeSpace;
            frm_Setting.ICount = icount;



            frm_Setting.CurrLimit = currLimit;
            frm_Setting.VoltMax = voltMax;
            frm_Setting.VoltMin = voltMin;
            frm_Setting.VoltSpace = voltSpace;
            frm_Setting.VTimeSpace = vTimeSpace;
            frm_Setting.VCount = vcount;
            



            frm_Setting.ShowDialog();

            if (frm_Setting.DialogResult == DialogResult.OK)
            {
                voltLimit = frm_Setting.VoltLimit;
                currMax = frm_Setting.CurrMax;
                currMin = frm_Setting.CurrMin;
                currSpace = frm_Setting.CurrSpace;
                iTimeSpace = frm_Setting.ITimeSpace;
                icount = frm_Setting.ICount;

                currLimit = frm_Setting.CurrLimit;
                voltMax = frm_Setting.VoltMax;
                voltMin = frm_Setting.VoltMin;
                voltSpace = frm_Setting.VoltSpace;
                vTimeSpace = frm_Setting.VTimeSpace;
                vcount = frm_Setting.VCount;

                



            }
        }

       private void tlMeasure_Click(object sender, EventArgs e)
        {
            if (!sourceIsJoin)
            {
                MessageBox.Show("电源未连接！", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            if (!chromeIsJoin)
            {
                MessageBox.Show("光强板未连接！", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            clear();

            threadMeasure = new Thread(measureSourceVolt);
            isMeasure = true;
            unableButton();
            threadMeasure.Start();
        }

        private void tlMeasure1_Click(object sender, EventArgs e)
        {
            if (!sourceIsJoin)
            {
                MessageBox.Show("电源未连接！", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            if (!chromeIsJoin)
            {
                MessageBox.Show("光强板未连接！", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            clear();

            threadMeasure = new Thread(measureSourceCurr);
            isMeasure = true;
            unableButton();
            threadMeasure.Start();

        }

        private void tlStop_Click(object sender, EventArgs e)
        {
            if (isMeasure)
            {
                classSourceMeter.LightOff();

                if (threadMeasure != null)
                {
                    if (threadMeasure.IsAlive)
                    {
                        threadMeasure.Abort();
                    }
                }

                BeginInvoke(new dlgShowButton(enableButton));

                isMeasure = false;

                MessageBox.Show("暂停测试！", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                MessageBox.Show("未进行测量！", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
        }
        

        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            for (int i = 1; i <= voltCheck.Length; )
            {
                display1();
                i++;
                a++;
            }
        }
        #endregion
    }
}
